package com.bl.student.dao.model.converter;

import com.bl.student.common.utils.JSONUtil;
import com.bl.student.dao.model.custom.DetailItem;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;

import javax.persistence.AttributeConverter;
import java.util.List;

public abstract class JsonConverter implements AttributeConverter<Object, String> {

    /**
     * DetailItem converter
     */
    public static class DetailItemListConverter extends JsonConverter {
        @Override
        TypeReference typeReference() {
            return new TypeReference<List<DetailItem>>() {};
        }
    }

    /** ==============================
     *  Converter definition
     ** ============================== **/

    abstract TypeReference typeReference();

    @Override
    public String convertToDatabaseColumn(final Object attribute) {
        if (attribute == null) {
            return null;
        }
        return JSONUtil.jsonEncode(attribute);
    }

    @Override
    public Object convertToEntityAttribute(final String dbData) {
        if (Strings.isNullOrEmpty(dbData)) {
            return null;
        }
        return JSONUtil.decodeJson(dbData, typeReference());
    }

}
